import { createRouter, createWebHistory } from "vue-router";
import store from "@/store";
import Cookies from "js-cookie";
//无需权限控制的路由
export const baseRouter = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login"),
    meta: { title: "登录" },
  },
];
//所有需要权限控制的路由
export const allRouter = [
  {
    path: "/",
    name: "index",
    component: () => import("@/views/index"),
    meta: { title: "首页" },
    isMenu: 1,
    children: [
      {
        path: "/work",
        name: "Home",
        component: () => import("@/views/Home"),
        meta: { title: "工作台" },
        isMenu: 1,
      },
      {
        path: "/system",
        name: "system",
        component: () => import("@/views/system/index"),
        meta: { title: "系统设置" },
        isMenu: 1,
        children: [
          {
            path: "basic-settings",
            name: "basicSettings",
            parentPath: "/system",
            component: () => import("@/views/system/BasicSetting"),
            meta: { title: "基础设置" },
            isMenu: 2,
          },
          {
            path: "regional-settings",
            parentPath: "/system",
            name: "regionalSettings",
            component: () => import("@/views/system/RegionalSetting"),
            meta: { title: "区域设置" },
            isMenu: 2,
          },
          {
            path: "department-setting",
            name: "departmentSetting",
            parentPath: "/system",
            component: () => import("@/views/system/DepartmentSetting"),
            meta: { title: "部门设置" },
            isMenu: 2,
          },
          {
            path: "operation-log",
            name: "operationLog",
            parentPath: "/system",
            component: () => import("@/views/system/OperationLog"),
            meta: { title: "操作日志" },
            isMenu: 2,
          },
          {
            path: "user-management",
            name: "userManagement",
            component: () =>
              import("@/views/system/userManagement/UserManagement"),
            meta: { title: "用户管理" },
            isMenu: 2,
            parentPath: "/system",
            children: [
              {
                path: "user-authorize",
                name: "UserAuthorize",
                component: () =>
                  import("@/views/system/userManagement/UserAuthorize"),
                meta: { title: "授权" },
              },
            ],
          },
          {
            path: "role-management",
            name: "roleManagement",
            parentPath: "/system",
            component: () => import("@/views/system/RoleManagement"),
            meta: { title: "角色管理" },
            isMenu: 2,
          },
          {
            path: "menu-management",
            name: "menuManagement",
            parentPath: "/system",
            component: () => import("@/views/system/MenuManagement"),
            meta: { title: "菜单管理" },
            isMenu: 2,
          },
        ],
      },
      {
        name: "canteen",
        path: "/canteen",
        component: () => import("@/views/canteen/Index"),
        meta: { title: "食堂管理" },
        isMenu: 1,
        children: [
          {
            name: "canteenSettings",
            path: "canteen-settings",
            parentPath: "/canteen",
            component: () =>
              import("@/views/canteen/CanteenSettings/CanteenSettings"),
            meta: { title: "食堂配置" },
            isMenu: 2,
            children: [
              {
                name: "CanteenEdit",
                path: "/canteen/canteen-edit",
                component: () =>
                  import("@/views/canteen/CanteenSettings/CanteenEdit"),
                meta: { title: "食堂编辑" },
              },
            ],
          },
          {
            name: "menuManger",
            path: "menu-manger",
            component: () => import("@/views/canteen/MenuManger/MenuManger"),
            meta: { title: "菜谱管理" },
            parentPath: "/canteen",
            isMenu: 2,
            children: [
              {
                path: "menu-edit",
                name: "MenuEdit",
                component: () => import("@/views/canteen/MenuManger/MenuEdit"),
                meta: { title: "菜谱编辑" },
              },
              {
                path: "menu-detail",
                name: "MenuDetail",
                component: () =>
                  import("@/views/canteen/MenuManger/MenuDetail"),
                meta: { title: "菜谱详情" },
              },
            ],
          },
          {
            name: "dishesManger",
            isMenu: 2,
            path: "dishes-manger",
            parentPath: "/canteen",
            component: () =>
              import("@/views/canteen/DishesManger/DishesManger"),
            meta: { title: "菜品管理" },
            children: [
              {
                path: "dishes-edit",
                name: "DishesEdit",
                component: () =>
                  import("@/views/canteen/DishesManger/DishesEdit"),
                meta: { title: "菜品编辑" },
              },
              {
                path: "dishes-detail",
                name: "DishesDetail",
                component: () =>
                  import("@/views/canteen/DishesManger/DishesDetail"),
                meta: { title: "菜品详情" },
              },
            ],
          },
          {
            name: "feedback",
            path: "feedback",
            isMenu: 2,
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Feedback/Feedback"),
            meta: { title: "意见反馈" },
            children: [
              {
                path: "feedback-detail",
                name: "feedbackDetail",
                component: () =>
                  import("@/views/canteen/Feedback/FeedbackDetail"),
                meta: { title: "意见详情" },
              },
              {
                path: "feedback-handle",
                name: "feedbackHandle",
                component: () =>
                  import("@/views/canteen/Feedback/FeedbackHandle"),
                meta: { title: "处理" },
              },
            ],
          },
          {
            name: "commentManger",
            path: "comment-manger",
            isMenu: 2,
            parentPath: "/canteen",
            component: () => import("@/views/canteen/CommentManger"),
            meta: { title: "评论管理" },
          },
          {
            name: "Audit",
            path: "audit",
            isMenu: 2,
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Audit/Audit"),
            meta: { title: "食堂审核" },
            children: [
              {
                path: "audit-detail",
                name: "auditDetail",
                component: () => import("@/views/canteen/Audit/Audit-detail"),
                meta: { title: "菜品审核" },
              },
              {
                path: "menu-audit",
                name: "menuAudit",
                component: () => import("@/views/canteen/Audit/MenuAudit"),
                meta: { title: "菜谱审核" },
              },
            ],
          },
          {
            name: "RoomManger",
            path: "RoomManger",
            isMenu: 2,
            parentPath: "/canteen",
            component: () => import("@/views/canteen/RoomManger/Index"),
            meta: { title: "包房管理" },
          },
          {
            name: "Meal",
            path: "Meal",
            isMenu: 2,
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Meal/Index"),
            meta: { title: "套餐管理" },
          },
          {
            path: "addMeal",
            name: "addMeal",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Meal/AddMeal"),
            meta: { title: "套餐配置" },
          },
          {
            path: "mealDetail",
            name: "mealDetail",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Meal/MealDetail"),
            meta: { title: "套餐详情" },
          },
          {
            path: "mealLabel",
            name: "mealLabel",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/MealLabel/Index"),
            meta: { title: "餐标管理" },
            isMenu: 2,
          },
          {
            path: "order",
            name: "order",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Order/Index"),
            meta: { title: "包房预约" },
            isMenu: 2,
          },
          {
            path: "orderRoom",
            name: "orderRoom",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Order/OrderRoom"),
            meta: { title: "预约" },
          },
          {
            path: "orderDetail",
            name: "orderDetail",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/Order/OrderDetail"),
            meta: { title: "预约详情" },
          },
          {
            path: "roomAudit",
            name: "roomAudit",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/RoomAudit/Index"),
            meta: { title: "包房审核" },
            isMenu: 2,
          },
          {
            path: "roomAuditDetail",
            name: "roomAuditDetail",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/RoomAudit/RoomAuitDetail"),
            meta: { title: "审核详情" },
          },
          {
            path: "auditUser",
            name: "auditUser",
            parentPath: "/canteen",
            component: () => import("@/views/canteen/AuditUser/Index"),
            meta: { title: "食堂审核人" },
          },
        ],
      },
      //    消息中心
      {
        name: "message",
        path: "/message",
        component: () => import("@/views/message/index"),
        meta: {
          title: "消息中心",
          isMenu: 1,
        },
        children: [
          {
            path: "notice",
            name: "notice",
            parentPath: "/message",
            component: () => import("@/views/message/notice/Notice"),
            meta: { title: "通知公告" },
            isMenu: 2,
          },
          {
            path: "notice-add",
            name: "noticeAdd",
            component: () => import("@/views/message/notice/addNotice"),
            meta: { title: "操作通知公告" },
            isMenu: 3,
          },
          {
            path: "notice-detail",
            name: "noticeDetail",
            component: () => import("@/views/message/notice/DetailNotice"),
            meta: { title: "通知公告详情" },
            isMenu: 3,
          },
          {
            path: "expose",
            name: "expose",
            parentPath: "/message",
            component: () => import("@/views/message/expose/index"),
            meta: { title: "曝光台" },
            isMenu: 2,
          },
          {
            path: "addExpose",
            name: "addExpose",
            parentPath: "/message",
            component: () => import("@/views/message/expose/AddExpose"),
            meta: { title: "曝光台信息" },
            isMenu: 3,
          },
          {
            path: "DetailExpose",
            name: "DetailExpose",
            parentPath: "/message",
            component: () => import("@/views/message/expose/DetailExpose"),
            meta: { title: "曝光台详情" },
            isMenu: 3,
          },
        ],
      },
    ],
  },
];
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: baseRouter,
});

//增加菜单重定向
function addRedirect(obj, authArray) {
  // 需要增加重定向的路由
  const routeList = ["/system", "/canteen", "/message"];
  //  筛选符合条件数据
  const index = routeList.indexOf(obj.path);
  if (index < 0) {
    return;
  } else {
    let redirectPath = "";
    const menuSet = new Set();
    authArray.map((item) => {
      menuSet.add(item);
    });
    for (let i = 0; i < menuList.length; i++) {
      const basePath = menuList[i].parentPath + "/" + menuList[i].path;
      if (basePath.indexOf(obj.path + "/") >= 0 && menuSet.has(basePath)) {
        redirectPath = basePath;
        break;
      }
    }
    obj.redirect = redirectPath;
  }
}
//存放二级菜单数据集合
const menuList = [];
function getleftMenu(nodes) {
  //循环遍历路由数据
  for (let item of nodes) {
    if (item.isMenu === 2) {
      menuList.push(item);
    }
    if (item.children && item.children.length) {
      getleftMenu(item.children); //如果存在子集，继续递归
    }
  }
}
//构造动态路由数据
function readTree(nodes, authArray, arr = []) {
  //循环遍历路由数据
  for (let item of nodes) {
    if (authArray.indexOf(item.path) === null) continue; //如果没有找到，结束本次循环
    let obj = { ...item, children: [] }; //定义一个对象
    arr.push(obj); //将找到的对象，放进数组中
    if (item.children && item.children.length) {
      addRedirect(obj, authArray);
      readTree(item.children, authArray, obj.children); //如果存在子集，继续递归
    }
  }
}
//定义增加路由至router的函数
function addRoutes(array) {
  // router.matcher = createRouter({ array }).matcher;
  let r = array[0];
  router.addRoute(r);
}
//定义调用递归和动态路由至router函数
function addToRouter() {
  //  menuRouteLoaded状态，如果为true直接return
  let menuRouteLoaded = store.state.menuList.menuRouteLoaded;
  let authorities = sessionStorage.getItem("authorities");
  // 已装载和权限为空直接返回  tsanyang  2021-11-11
  if (menuRouteLoaded) return;
  // 定义接收动态路由数据  tsanyang  2021-11-11
  let dynamicRouterArray = [];
  let authArray = JSON.parse(authorities);
  getleftMenu(allRouter);
  // 根据权限控制路由数据和权限结合生成动态路由  tsanyang  2021-11-11
  readTree(allRouter, authArray, dynamicRouterArray);
  // 装载路由数据至路由表  tsanyang  2021-11-11
  addRoutes(dynamicRouterArray);
  // 修改路由为已装载状态 tsanyang  2021-11-11
  store.commit("menuRouteLoaded", true);
}

//全局路由导航守卫
router.beforeEach((to, form, next) => {
  const token = Cookies.get("token");
  //  如果有token
  if (token) {
    //  如果是登录页面就放行到首页
    if (to.path === "/login") {
      next({ path: "/" });
    }
    //  保存在store中的menuRouteLoaded状态为true，直接放行
    if (store.state.menuList.menuRouteLoaded) {
      next();
    } else {
      addToRouter();
      // 如果addRoutes并未完成，直到addRoutes完成
      //防止我们构造的动态路由没有完成，导致访问空白页
      next({ ...to, replace: true });
    }
  } else {
    // 未登录时
    if (to.path !== "/login") {
      next({ path: "/login" });
    } else {
      next();
    }
  }
});
export default router;
